import axiosIns from '../../utils/axios';
import update, { updateChain } from 'immutability-helper-x';
import { messageList, delMessage } from '../../utils/mock';
/**
|--------------------------------------------------
|  Constants
|--------------------------------------------------
*/
const GETLIST = 'GETLIST';
const MSG_LOADING = 'MSG_LOADING';
const DELETED = 'DELETED';
/**
|--------------------------------------------------
| Actions
|--------------------------------------------------
*/
export function getMessageList() {
  return async (dispatch, getState) => {
    const { loading } = getState().message;
    if (loading) return;
    dispatch(fetching());
    const res = await axiosIns('/getMessageList');
    const { data } = res;
    dispatch(getListSuccess(data));
  };
}
export function deleteMsg(item) {
  return async (dispatch, getState) => {
    const res = await axiosIns('/delMessage');
    const { list } = getState().message;
    let list_copy = [].concat(list);
    for (let [index, _item] of list_copy.entries()) {
      if (_item.id == item.id) {
        list_copy.splice(index, 1);
        break;
      }
    }
    dispatch(deleteSuccess({ list: list_copy }));
  };
}

function deleteSuccess(data) {
  return {
    type: DELETED,
    list: data.list
  };
}

function getListSuccess(data) {
  return {
    type: GETLIST,
    list: data.list
  };
}

function fetching() {
  return {
    type: MSG_LOADING
  };
}
/**
|--------------------------------------------------
| Action Handlers
|--------------------------------------------------
*/
const ACTION_HANDLERS = {
  [MSG_LOADING]: state => {
    return { ...state, loading: true };
  },
  [GETLIST]: (state, action) => {
    return { ...state, loading: false, list: action.list };
  },
  [DELETED]: (state, action) => {
    return { ...state, list: action.list };
  }
};
/**
|--------------------------------------------------
| Reducer
|--------------------------------------------------
*/
const initialState = {
  loading: false,
  list: null
};
export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type];
  return handler ? handler(state, action) : state;
}
